/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.node;

import java.util.Collection;
import java.util.LinkedHashMap;

import jp.aist.gtrc.plus.scheduler.status.NodeStatus;

public class NodeInfoMap {

	private final LinkedHashMap<String, NodeInfo> nodeMap;

	NodeInfoMap() {

		nodeMap = new LinkedHashMap<String, NodeInfo>();

	}

	public NodeInfo get(String hostname) {

		return nodeMap.get(hostname);

	}

	public void remove(NodeInfo info) {

		nodeMap.remove(info.getName());

	}

	public PhysicalNodeInfo getPhysicalNodeInfo(String hostname) {

		NodeInfo node = get(hostname);
		return (node != null) ? node.getPhysicalNodeInfo() : null;

	}

	private synchronized void addNodeToMap(NodeInfo info) {

		String key = info.getName();
		nodeMap.put(key, info);

	}

	void addNode(NodeStatus status) {

		if (nodeMap.containsKey(status.getName()) == false) {
			NodeInfo info = new NodeInfo(status);
			addNodeToMap(info);
		} else {
			assert(false);
		}

	}

	synchronized void changeNodeInfoPair(NodeInfo infoA, NodeInfo infoB) {

		if ((infoA != null) && (infoB != null)) {
			/*
			 * Swap PhysicalNodeInfo object on nodeMap.
			 * BEFORE:
			 * 		infoA[pInfoA], infoB[newPInfo]
			 * AFTER:
			 * 		infoA[newPInfo], infoB[pInfoA]
			 *
			 * nodeIndexMap never changed.
			 */
			PhysicalNodeInfo pInfoA = infoA.getPhysicalNodeInfo();
			PhysicalNodeInfo pInfoB = infoB.getPhysicalNodeInfo();
			infoA.changePhysicalNodeInfo(pInfoB);
			infoB.changePhysicalNodeInfo(pInfoA);
		} else {
			assert(false);
		}

	}

	public Collection<NodeInfo> getNodes() {

		return nodeMap.values();

	}

	public int size() {

		return nodeMap.size();

	}

}
